import Card from '@/components/Card';
import Description from '@/components/Description';
import Empty from '@/components/Empty';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { Flex } from 'antd';
import type { DescriptionsProps } from 'antd/es/descriptions';
import React, { useEffect, useState } from 'react';
import { useIntl } from 'umi';
import Style from '../../index.less';

interface propsType {
  data?: API.EmmuVo['airConditionings'];
}
const Index: React.FC<propsType> = ({ data }) => {
  const [Options, setOptions] = useState({
    type1: [],
    type2: [],
    online: [],
    faultstatus: [],
    equipStatus: [],
  });
  const [isEmpty, setEmpty] = useState(false);
  const intl = useIntl();
  const overallStateCopy = [
    {
      key: 'equipmentWorkingStatus',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.deviceWorkStatus' }),
      children: '',
    },
    {
      key: 'indoorFanStatus',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.indoorFanStatus' }),
      children: '',
    },
    {
      key: 'outdoorFanStatus',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.outdoorFanStatus' }),
      children: '',
    },
    {
      key: 'compressorStatus',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.compressorStatus' }),
      children: '',
    },
    {
      key: 'electricHeatingOperationStatus',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.electricHeaterStatus' }),
      children: '',
      span: 1,
    },
  ];

  const overallSensorCopy = [
    {
      key: 'defrostingTemperature',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.defrostTemp' }),
      children: '',
    },
    {
      key: 'condensingTemperature',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.condensationTemp' }),
      children: '',
    },
    {
      key: 'temperatureOutsideCabinet',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.outsideTemp' }),
      children: '',
    },
    {
      key: 'temperatureInsideCabinet',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.insideTemp' }),
      children: '',
    },
    {
      key: 'humidityInsideCabinet',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.insideHumidity' }),
      children: '',
    },
    {
      key: 'airOutletTemperature',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.outletTemp' }),
      children: '',
      span: 1,
    },
  ];

  const overallParamsCopy = [
    {
      key: 'coolingTemperatureDifference',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.coolingTempDiff' }),
      children: '',
    },
    {
      key: 'refrigerationHysteresis',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.coolingReturnDiff' }),
      children: '',
    },
    {
      key: 'heatingTemperature',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.heatingTemp' }),
      children: '',
    },
    {
      key: 'heatingHysteresis',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.heatingReturnDiff' }),
      children: '',
    },
    {
      key: 'highTemperaturePoint',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.highTempPoint' }),
      children: '',
    },
    {
      key: 'lowTemperaturePoint',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.lowTempPoint' }),
      children: '',
    },
    {
      key: 'humiditySetting',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.humiditySetting' }),
      children: '',
    },
    {
      key: 'humidityHysteresis',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.humidityReturnDiff' }),
      children: '',
    },
    {
      key: 'highHumidityPoint',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.highHumidityPoint' }),
      children: '',
      span: 1,
    },
  ];

  const baseInfoCopy = [
    {
      key: 'enable',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.isEnable' }),
      children: '',
    },
    {
      key: 'onlineState',
      label: intl.formatMessage({ id: 'data.onlineStatus' }),
      children: '',
    },
    {
      key: 'faultState',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.faultStatus' }),
      children: '',
    },
    {
      key: 'equipmentModel',
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.deviceModel' }),
      children: '',
      span: 1,
    },
  ];

  const [overallState, setoverallState] = useState<DescriptionsProps['items']>(overallStateCopy);
  const [overallSensor, setoverallSensor] = useState<DescriptionsProps['items']>(overallSensorCopy);
  const [overallParams, setoverallParams] = useState<DescriptionsProps['items']>(overallParamsCopy);
  const [baseInfo, setbaseInfo] = useState<DescriptionsProps['items']>(baseInfoCopy);
  const [isDataLoaded, setIsDataLoaded] = useState(false);

  const changeFuntion = (key: any, result: any) => {
    const array_workingState = ['compressorStatus', 'electricHeatingOperationStatus']; // 使用工作状态字典的字段
    const array_equipStatus = ['indoorFanStatus', 'outdoorFanStatus', 'equipmentWorkingStatus']; // 使用设备状态字典的字段
    const array2 = ['enable'];
    const array_onlineState = ['onlineState'];
    const array_faultState = ['faultState'];

    if (array_workingState.includes(key)) {
      return Options.type1.find((res) => res.value === result)?.['label'] || null; // WORKING_STATE_OF_DEHUMIDIFICATION
    } else if (array_equipStatus.includes(key)) {
      return Options.equipStatus.find((res) => res.value === result)?.['label'] || null; // AIR_CONDITIONING_EQUIPMENT_STATUS
    } else if (array2.includes(key)) {
      return Options.type2?.find((res) => res.value === result)?.['label'] || null;
    } else if (array_onlineState.includes(key)) {
      return Options.online?.find((res) => res.value === result)?.['label'] || null;
    } else if (array_faultState.includes(key)) {
      return Options.faultstatus?.find((res) => String(res.value) === result)?.['label'] || null;
    } else {
      return result;
    }
  };

  const changeContent = (data) => {
    if (data && data?.length) {
      const desc1 = overallStateCopy
        .map((item) => {
          return {
            ...item,
            children:
              data?.[0]?.airConditioningStatus?.[item.key] ||
              data?.[0]?.airConditioningStatus?.[item.key] === 0
                ? changeFuntion(item.key, data?.[0]?.airConditioningStatus?.[item.key])
                : null,
          };
        })
        .filter((res) => res.children !== null);
      setoverallState(desc1);

      const desc2 = overallSensorCopy
        .map((item) => {
          return {
            ...item,
            children:
              data?.[0]?.AirConditioningSensor?.[item.key] ||
              data?.[0]?.AirConditioningSensor?.[item.key] === 0
                ? changeFuntion(item.key, data?.[0]?.AirConditioningSensor?.[item.key])
                : null,
          };
        })
        .filter((res) => res.children !== null);
      setoverallSensor(desc2);

      const desc3 = overallParamsCopy
        .map((item) => {
          return {
            ...item,
            children:
              data?.[0]?.airConditioningOperatingParameters?.[item.key] ||
              data?.[0]?.airConditioningOperatingParameters?.[item.key] === 0
                ? changeFuntion(item.key, data?.[0]?.airConditioningOperatingParameters?.[item.key])
                : null,
          };
        })
        .filter((res) => res.children !== null);
      setoverallParams(desc3);

      const desc4 = baseInfoCopy
        .map((item) => {
          return {
            ...item,
            children:
              data?.[0]?.airConditioningBasicInformation?.[item.key] ||
              data?.[0]?.airConditioningBasicInformation?.[item.key] === 0
                ? changeFuntion(item.key, data?.[0]?.airConditioningBasicInformation?.[item.key])
                : null,
          };
        })
        .filter((res) => res.children !== null);
      setbaseInfo(desc4);

      if (!desc1.length && !desc2.length && !desc3.length && !desc4.length) {
        setEmpty(true);
      } else {
        setEmpty(false);
      }
    } else {
      setEmpty(true);
    }
  };

  // 修改 useEffect 中的字典获取
  useEffect(() => {
    if (!isDataLoaded) {
      Promise.all([
        fetchDictInfo(DATABASE_TYPE_ENUM.WORKING_STATE_OF_DEHUMIDIFICATION, true), // type1
        fetchDictInfo(DATABASE_TYPE_ENUM.ENABLE_DEVI, true), // type2
        fetchDictInfo(DATABASE_TYPE_ENUM.ONLINE_STATUS, true), // online
        fetchDictInfo(DATABASE_TYPE_ENUM.DEHUMIDIFICATION_FAULT_STATE, true), // faultstatus
        fetchDictInfo(DATABASE_TYPE_ENUM.AIR_CONDITIONING_EQUIPMENT_STATUS, true), // equipStatus
      ]).then((res) => {
        setOptions({
          type1: res[0], // WORKING_STATE_OF_DEHUMIDIFICATION
          type2: res[1], // ENABLE_DEVI
          online: res[2], // ONLINE_STATUS
          faultstatus: res[3], // DEHUMIDIFICATION_FAULT_STATE
          equipStatus: res[4], // AIR_CONDITIONING_EQUIPMENT_STATUS
        });
        setIsDataLoaded(true);
      });
    }
  }, []);

  useEffect(() => {
    if (isDataLoaded && data) {
      changeContent(data);
    }
  }, [isDataLoaded, data]);

  useEffect(() => {
    changeContent(data);
  }, [data]);

  const column = { xxl: 3, xl: 2, lg: 1, md: 1, sm: 1 };

  return (
    <div
      style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap: 0,
        flexDirection: 'column',
      }}
    >
      {!isEmpty ? (
        <>
          {overallState?.length ? (
            <Card
              title={intl.formatMessage({
                id: 'diagnosticPrediction.analysis.plantStatusAssessment',
              })}
              className={Style.CardStyle}
            >
              <Description items={overallState} column={column} />
            </Card>
          ) : null}

          {overallSensor?.length ? (
            <Card
              title={intl.formatMessage({ id: 'stationRealtimeMonitoring.sensor' })}
              className={Style.CardStyle}
            >
              <Description items={overallSensor} column={column} />
            </Card>
          ) : null}

          {overallParams ? (
            <Card
              title={intl.formatMessage({ id: 'stationRealtimeMonitoring.operation' })}
              className={Style.CardStyle}
            >
              <Description items={overallParams} column={column} />
            </Card>
          ) : null}

          {baseInfo?.length ? (
            <Card
              title={intl.formatMessage({ id: 'stationRealtimeMonitoring.info' })}
              className={Style.CardStyle}
            >
              <Description items={baseInfo} column={column} />
            </Card>
          ) : null}
        </>
      ) : (
        <Flex
          justify="center"
          align="center"
          style={{ width: '100%', height: '100%', marginTop: '290px' }}
        >
          <Empty />
        </Flex>
      )}
    </div>
  );
};

export default Index;
